<template>
  <el-dialog :title="title" :visible="dialogVisible" :before-close="onClose">
    <!-- form元素中只有一个输入框时，在该输入框中按下回车应提交该表单 -->
    <el-form
      ref="addForm"
      :model="formPo"
      :rules="rules"
      label-width="120px"
      size="small"
      @submit.native.prevent
    >
      <el-form-item label="属性值名称：" prop="propertyValue">
        <el-input
          v-model.trim="formPo.propertyValue"
          placeholder="输入属性值名称"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        size="small"
        @click="onSave"
      >确定</el-button>
      <el-button size="small" @click="onClose">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    curItem: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      title: '',
      formPo: {
        id: '',
        propertyValue: ''
      },
      rules: {
        propertyValue: [
          {
            required: true,
            message: '请输入属性值名称',
            trigger: 'blur'
          },
          { max: 20, message: '不建议超过20个字', trigger: 'blur' }
        ],
        serviceFeeRate: [
          {
            required: false,
            message: '请输入数字，最多带两位小数',
            pattern: /(^[\d]|^[1-9][\d]*)($|[\\.][\d]{0,2}$)/
          }
        ]
      }
    }
  },
  watch: {
    curItem: {
      handler(newVal) {
        this.formPo.id = newVal.id || ''
        this.formPo.propertyValue = newVal.propertyValue || ''
        this.title = newVal.propertyValue ? '编辑属性' : '新增属性'
      },
      deep: true
    }
  },
  methods: {
    onSave() {
      this.$refs.addForm.validate(valid => {
        if (!valid) {
          return false
        }
        this.$refs.addForm.clearValidate()
        this.$emit('handle-ok', { ...this.formPo })
      })
    },
    onClose() {
      this.$refs.addForm.resetFields()
      this.$refs.addForm.clearValidate()
      this.$emit('close-dialog')
    }
  }
}
</script>

<style scoped></style>
